<?php
 /**
 * 控制到用户权限
 *
 * LICENSE: 
 * @author $Id$
 * @since      Release 1.0.0
 * @copyright  Copyright (c) 2010-2011 Mumayi.com Inc. (http://www.mumayi.com)
*/
require_once	'Zend/Controller/Plugin/Abstract.php';
class Custom_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
		protected $roleid=100;
		function __construct($roleid) {
			
			if(isset($roleid)){
				$this->roleid=$roleid;
			}else{
				//普通用户
				$this->roleid=100;
			}
		}
	
		public function getAcl(){
			
			
			$moduleName=strtolower(Zend_Controller_Front::getInstance()->getRequest()->getModuleName());
			$controllerName=strtolower(Zend_Controller_Front::getInstance()->getRequest()->getControllerName());
			$actionName=strtolower(Zend_Controller_Front::getInstance()->getRequest()->getActionName());
			
			$Nowresource=$moduleName.':'.$controllerName;
			
			//取到全员权限
			$resource=new Resource();
			$acl=new Acl();
			$Role=new Role();
			$resources=$acls=array();
			
			$roleName=$this->roleid;
			
			$Zacl = new Zend_Acl();
			$Zacl->addRole(new Zend_Acl_Role($roleName));
			
			//取到此用户组，所有组id
			$idArr=$Role->getChildren($this->roleid,true);
			//生成组分类id列表
			$idList=implode(',',array_keys($idArr));
			
			$where="roleid IN ($idList) ";
			$data=$acl->fetchAll($where,'id DESC')->toArray();
			
			if(is_array($data))foreach($data as $vals){
				$aclarr=explode(',',$vals['resourceid']);
				foreach($aclarr as $val){
					$acls[]=$val;
				}
			}
			//去掉为空与复权限id
			$resourceid=array_unique(array_filter($acls));
			
			$resourceList=implode(',',$resourceid);
		
			
			//取到所有的资源，先注册资源
			$allResource=$resource->getResource("module='".$moduleName."'");
			$Zacl->add(new Zend_Acl_Resource('admin'));
			if(is_array($allResource))foreach ($allResource as $val) {
				$resourceID=$val['module'].':'.$val['controller'];
				$Zacl->add(new Zend_Acl_Resource($resourceID),$val['module']);
			}
			
			//再取到此用户组的权限，先取全量权限，再注册
			$result=$resource->fetchAll("id IN ($resourceList) AND action!=''")->toArray();
			if(is_array($result))foreach ($result as $name){
				$resourceID=$name['module'].':'.$name['controller'];
				$Zacl->allow($roleName, $resourceID, $name['action']);
			}
			
			//再取私有权限，进行注册
			$result=$resource->fetchAll("id IN ($resourceList) AND action=''")->toArray();
			if(is_array($result))foreach ($result as $name){
				$resourceID=$name['module'].':'.$name['controller'];
				$Zacl->allow($roleName,$resourceID);
			}
			
			//return $Zacl->isAllowed($roleName, $Nowresource,$actionName) ? 'allowed' : 'denied';
			return $Zacl->isAllowed($roleName, $Nowresource,$actionName);
			
		}
}